package com.youren.health.sercurity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.youren.health.pojo.Permission;
import com.youren.health.pojo.Role;
import com.youren.health.pojo.User;
import com.youren.health.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @program: health_parent
 * @author: You_ren_a
 * @create: 2020-11-30 23:27
 **/

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        SimpleGrantedAuthority simpleGrantedAuthority=null;
        if (user!=null) {
            //密码
            String password = user.getPassword();
            //创建授权集合
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            Set<Role> roles = user.getRoles();
            if (roles!=null) {
                for (Role role : roles) {
                    simpleGrantedAuthority=new SimpleGrantedAuthority(role.getKeyword());
                    authorities.add(simpleGrantedAuthority);
                    Set<Permission> permissions = role.getPermissions();
                    if (permissions!=null) {
                        for (Permission permission : permissions) {
                            simpleGrantedAuthority=new SimpleGrantedAuthority(permission.getKeyword());
                            authorities.add(simpleGrantedAuthority);
                        }
                    }
                }
            }
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
            return userDetails;
        }
        return null;
    }
}
